package com.zh.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.common.utils.PageUtils;
import com.zh.common.utils.Query;
import com.zh.gulimall.product.dao.CategoryDao;
import com.zh.gulimall.product.entity.CategoryEntity;
import com.zh.gulimall.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithThree() {
        // 查处所有的分类
        // 组装父子的树形结构
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> menu = categoryEntities.stream()
                .filter(item->item.getParentCid() == 0)
                .map((j) -> {
                    j.setChildren(getChildrens(j, categoryEntities));
                    return j;
                })
                .sorted(Comparator.comparingInt(CategoryEntity::getSort)).collect(Collectors.toList());
        return menu;
    }

    @Override
    public void removeMenuByCatIds(List<Long> asList) {
        // TODO 1.检查当前删除菜单 是否被别的地方引用
        baseMapper.deleteBatchIds(asList);

    }

    // 递归查找当前菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity entity, List<CategoryEntity> categoryEntities) {
        return categoryEntities.stream().filter(item -> item.getParentCid().equals(entity.getCatId())).map((j) -> {
            j.setChildren(getChildrens(j, categoryEntities));
            return j;
        }).sorted(Comparator.comparingInt(CategoryEntity::getSort)).collect(Collectors.toList());
    }
}